package com.example.index.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatTextView
import com.example.index.R

/**
 *@author hiray
 */
class IndexItemAdapter(private var items: List<String>, private var onItemClickListener: OnItemClickListener?) :
    androidx.recyclerview.widget.RecyclerView.Adapter<IndexItemAdapter.ItemViewHolder>() {

    private var layoutInflater: LayoutInflater? = null
    private val layoutId = R.layout.demo_item
    var cornerMarker: Boolean = false

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        if (layoutInflater == null)
            layoutInflater = LayoutInflater.from(parent.context)
        return ItemViewHolder(
            layoutInflater!!.inflate(
                layoutId,
                parent,
                false
            )
        )
    }

    override fun getItemCount(): Int {
        return items.size
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        if (cornerMarker) {
            holder.cornerMarker.visibility = View.VISIBLE
            holder.cornerMarker.text = holder.adapterPosition.toString()
        } else holder.cornerMarker.visibility = View.GONE
        holder.textView.text = items[holder.adapterPosition]
        if (onItemClickListener != null)
            holder.itemView.setOnClickListener {
                onItemClickListener!!.onItemClick(holder.adapterPosition)
            }
    }


    class ItemViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
        var textView: AppCompatTextView = itemView.findViewById(R.id.item_name) as AppCompatTextView
        var cornerMarker: AppCompatTextView = itemView.findViewById(R.id.corner_marker) as AppCompatTextView
    }


    interface OnItemClickListener {
        fun onItemClick(position: Int): Unit
    }
}